package com.bwf.lgqingdan.gui.activity;

import android.annotation.TargetApi;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.bwf.lgqingdan.R;
import com.bwf.lgqingdan.entity.ArticlesBean;
import com.bwf.lgqingdan.gui.adapter.PopSortListAdapter;
import com.bwf.lgqingdan.gui.adapter.TagDetailsArticlesRecycleViewAdapter;
import com.bwf.lgqingdan.gui.adapter.base.BaseRecycleViewAdapter;
import com.bwf.lgqingdan.mvp.presenter.ArticleListPresenter;
import com.bwf.lgqingdan.mvp.presenter.impl.ArticleListPresenterImpl;
import com.bwf.lgqingdan.mvp.view.ArticleListView;
import com.bwf.lgqingdan.utils.IntentUtils;
import com.cjj.MaterialRefreshLayout;
import com.cjj.MaterialRefreshListener;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2016/11/18.
 */

public class ArticleListActivity extends ActivityBase implements ArticleListView, BaseRecycleViewAdapter.OnItemClickListener<ArticlesBean> {
    @BindView(R.id.root)
    View root;
    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.img_title_right)
    ImageView imgTitleRight;
    @BindView(R.id.recycleView)
    RecyclerView recycleView;
    @BindView(R.id.refreshLayout)
    MaterialRefreshLayout refreshLayout;
    @BindView(R.id.view_cover)
    View viewCover;
    @BindView(R.id.title)
    TextView title;
    private ArticleListPresenter presenter;
    public static final String TAG_CATEGORY_ID = "categoryId";
    private int categoryId;
    private TagDetailsArticlesRecycleViewAdapter articlesRecycleViewAdapter;
    LinearLayoutManager linearLayoutManager;
    @Override
    public int getContentViewResID() {
        return R.layout.activity_article_list;
    }

    @Override
    protected void initViews() {
        ButterKnife.bind(this);
        root.setPadding(0, getStatusHeight(), 0, 0);
        title.setText(getString(R.string.article_list));
        linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recycleView.setLayoutManager(linearLayoutManager);
        refreshLayout.setLoadMore(true);
        refreshLayout.setMaterialRefreshListener(new MaterialRefreshListener() {
            @Override
            public void onRefresh(MaterialRefreshLayout materialRefreshLayout) {
                loadInitData();
            }

            @Override
            public void onRefreshLoadMore(MaterialRefreshLayout materialRefreshLayout) {
                super.onRefreshLoadMore(materialRefreshLayout);
                loadNextData();
            }
        });
    }

    private void loadInitData() {
        presenter.loadInitArticles();
    }

    private void loadNextData() {
        presenter.loadNextPageArticles();
    }

    @Override
    protected void initDatas() {
        categoryId = getIntent().getIntExtra(TAG_CATEGORY_ID, 0);
        presenter = new ArticleListPresenterImpl(categoryId, this);
        articlesRecycleViewAdapter = new TagDetailsArticlesRecycleViewAdapter(this);
        articlesRecycleViewAdapter.setOnItemClickListener(this);
        recycleView.setAdapter(articlesRecycleViewAdapter);
        new Handler() {
            @Override
            public void handleMessage(Message msg) {
                refreshLayout.autoRefresh();
            }
        }.sendEmptyMessageDelayed(0, 350);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @OnClick({R.id.back, R.id.img_title_right})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.img_title_right:
                showSortPop();
                break;
        }
    }

    @Override
    public void showLoadArticlesFailed(String failedMsg) {
        refreshLayout.finishRefresh();
        refreshLayout.finishRefreshLoadMore();
    }

    @Override
    public void showLoadArticlesSuccess(int page, List<ArticlesBean> articles) {
        if (page == 1) {
            articlesRecycleViewAdapter.setDatas(articles);
            refreshLayout.finishRefresh();
            linearLayoutManager.scrollToPosition(0);
        } else {
            articlesRecycleViewAdapter.addDatas(articles);
            refreshLayout.finishRefreshLoadMore();
        }

    }

    @Override
    public void showNoMoreArticles() {
        Toast.makeText(this, getString(R.string.noMoreData), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onItemClick(int position, View view, ArticlesBean data) {
        IntentUtils.gotoArticleDetailActivity(this, data.getId());
    }


    private PopupWindow popupWindowSort;
    private PopSortViewHolder popSortViewHolder;

    /**
     * 显示 排序的PopupWindow
     */
    @TargetApi(Build.VERSION_CODES.KITKAT)
    public void showSortPop() {
        if (popupWindowSort == null) {
            popupWindowSort = new PopupWindow(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);
            View view = LayoutInflater.from(this).inflate(R.layout.layout_pop_sort, null);
            popSortViewHolder = new PopSortViewHolder(view);
            popupWindowSort.setContentView(view);
            popupWindowSort.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    viewCover.setVisibility(View.GONE);
                }
            });
            popupWindowSort.setFocusable(true);
            /**
             * 如果有背景，则会在contentView外面包一层PopupViewContainer之后作为mPopupView，如果没有背景，则直接用contentView作为mPopupView。
             而这个PopupViewContainer是一个内部私有类，它继承了FrameLayout，在其中重写了Key和Touch事件的分发处理
             */
            popupWindowSort.setBackgroundDrawable(new ColorDrawable(0x00000000));
        }
        viewCover.setVisibility(View.VISIBLE);
        popupWindowSort.showAsDropDown(findViewById(R.id.img_title_right), 0, -20, Gravity.RIGHT);//sdk>=19
    }

    class PopSortViewHolder implements AdapterView.OnItemClickListener {
        @BindView(R.id.listview_pop_sort)
        ListView listviewPopSort;
        PopSortListAdapter sortListAdapter;

        PopSortViewHolder(View view) {
            ButterKnife.bind(this, view);
            sortListAdapter = new PopSortListAdapter(view.getContext());
            String[] strings = getResources().getStringArray(R.array.articles_sort_texts);
            for (String text : strings) {
                sortListAdapter.getDatas().add(text);
            }
            listviewPopSort.setAdapter(sortListAdapter);
            listviewPopSort.setOnItemClickListener(this);
        }

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            if (sortListAdapter.setSelectedPosition(position)) {
                switch (position) {
                    case 0:
                        presenter.loadNextPageArticlesSortByDefault();
                        break;
                    case 1:
                        presenter.loadNextPageArticlesSortByNewest();
                        break;
                    case 2:
                        presenter.loadNextPageArticlesSortByHottest();
                        break;
                }
//                isNoMoreData = false;
            }
            popupWindowSort.dismiss();
        }
    }
}
